package com.fkcai.hansoul.service.impl;

import com.fkcai.hansoul.common.exception.ComFoundException;
import com.fkcai.hansoul.common.util.ResultCode;
import com.fkcai.hansoul.service.FileService;
import com.fkcai.hansoul.common.util.FileUtil;
import com.fkcai.hansoul.common.util.OssUtil;
import com.fkcai.hansoul.common.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * 文件上传业务逻辑实现类
 */
@Service
public class FileServiceImpl implements FileService {
	@Autowired
	private OssUtil ossUtil;
	
	
	/**
	 * 实现文件上传
	 * @param file 文件
	 * @param fileType 文件类型
	 * @return 文件路径
	 */
	@Override
	public String uploadFile (MultipartFile file, String fileType) {
		String userId = ThreadLocalUtil.get();
		String originalFilename = file.getOriginalFilename();
		String fileExtension = FileUtil.getFileExtension(originalFilename);
		String uuid = UUID.randomUUID().toString().replace("-", "");
		
		try {
			String objectName = "postFile/user_" + userId + "/" + uuid + "." + fileExtension;
			String url = ossUtil.uploadFile(file.getInputStream(), objectName);
			
			return url;
		} catch (Exception e) {
			throw new ComFoundException(ResultCode.FILE_UPLOAD_ERROR);
		}
	}
	
	@Override
	public void deleteFile (String fileUrl) {
		try {
			String objectName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
			ossUtil.deleteFile(objectName);
			
		} catch (Exception e) {
			throw new ComFoundException(ResultCode.FILE_DELETE_ERROR);
		}
	}
}
